const axios = require('axios')
const { Service } = require('ee-core');
const Log = require('ee-core/log');
const fs = require('fs'); 
const Conf = require('ee-core/config');
const fast_down = require('../third/fast-down');
const path = require('path');


const cfg = Conf.getValue('platformApi');



/**
 * DownloadService
 * @class
 */
class DownloadService extends Service {

  constructor(ctx) {
    super(ctx);
  }
  
  async getFileSize(url) {
      try {
          const response = await axios.head(url);
          if (response && response.headers['content-length']) {
              return parseInt(response.headers['content-length']); // 返回文件大小（字节数）
          } else {
              throw new Error("无法获取文件大小");
          }
      } catch (error) {
          console.log(error);
      }
  }
  
  /** 下载
   * @param {String} relativeUrl 如 'profile/2024/01/01/sss.png'
   * @param {String} fileSavePath 如 'd:\ss\sss.png'
   */
  async download(relativeUrl, fileSavePath) {
	try{
		let downUrl = cfg.url + relativeUrl;
		Log.info("下载地址:"+downUrl);
		let total_bytes = this.getFileSize(downUrl);
		let received_bytes =  0;
		if (fs.existsSync(fileSavePath)) {
			let stats = fs.statSync(fileSavePath);//如果文件已存在读取文件信息
			if(total_bytes == stats.size){//如果文件已经存在并且已经下载按成则跳过该文件
				return;
			}
			received_bytes = stats.size;
		}

		let params = {
			url: downUrl,
			// headers: {
			//   'Content-Type': 'multipart/form-data',
			// },
			onDownloadProgress:  (e) => {
				console.log('e:',e);
				// e是一个包含下载进度信息的事件对象，其中包括loaded 、total属性：
				// this.percentComplete = Math.floor((e.loaded / e.total) * 100)
			},
			responseType: 'arraybuffer',
		};
		if(received_bytes > 0){
			params.headers['Range'] = 'bytes=' + received_bytes;
		}
		// 发起下载请求
		let { data } = await axios(params);
		await fs.promises.writeFile(fileSavePath, data, 'binary');
		
	}catch (err){
		Log.error("axios download exception:"+err)
	}
  }

  /**
   * 下载
   * @param {String} relativeUrl 
   * @param {String} fileSavePath 
   */
  async downloadFast(relativeUrl, fileSavePath) {
	  let con_num = 4;
	  let stime = new Date().getTime();
	  console.log('start download, concurrency: ' + con_num);
      let downUrl = cfg.url + relativeUrl;
	  let tmpDir = path.dirname(fileSavePath);
	  let fileName = path.basename(fileSavePath);
	  // 下载文件已存在则返回true
	  if (fs.existsSync(fileSavePath)) {
		return true;
	  }
	  Log.info("tmpDir:"+ tmpDir);
	  var downloader = new fast_down.Downloader(downUrl, fileSavePath, {
		'concurrency': con_num,
		'progress_throttle': 4000,
		'tmpdir': tmpDir
	  });

	  downloader.onProgress((pct, tinfo, pinfo) => {
		console.log('progress:',pct);
	  });

	  let ret = await downloader.download();
	  console.log('download ' + (ret ? 'success' : 'fail') + ', cost: ' + (new Date().getTime() - stime) + 'ms');
	  return ret;
  }
  
}

DownloadService.toString = () => '[class DownloadService]';
module.exports = DownloadService;  
  
// module.exports = service
